<?php
/*
    Create by zhangxl
*/
header('Content-type:text');
define("TOKEN", "weixin");
$wechatObj = new wx_sample_test();
if (isset($_GET['echostr'])) {
    $wechatObj->valid();
}else{
    $wechatObj->responseMsg();
}

class wx_sample_test extends CI_Controller
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            header('content-type:text');
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);
            switch($RX_TYPE)
                {
                    case "text":
                        $resultStr = $this->handleText($postObj);
                        break;
                    case "event":
                        $resultStr = $this->handleEvent($postObj);
                        break;
                    default:
                        $resultStr = "Unknow msg type: ".$RX_TYPE;
                        break;
                }
            echo $resultStr;
        }else{
            echo "";
            exit;
        }
    }
    
    public function handleText($postObj){
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);

        $ev = $postObj->Event;

        $time = time();
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>0</FuncFlag>
                    </xml>";
        $keyword = strtoupper(trim($keyword));
        if($this->DataFormat($keyword)){
            $arr = $this->getDateArr($keyword);
            if(strstr($arr[0], "DMZ"))
            {
                //$arr = $this->getDateArr($keyword);
                $res = $this->getScoreByConnectSQL($arr[0],$arr[1]);
                if($res){
                    $contentStr = "您查询到的信息是："."\n".
                                    "准考证号:".$res['examnum']."\n".
                                    "姓名：".$res['username']."\n".
                                    "学校：".$res["school"]."\n".
                                    "年级：".$res['class']."\n".
                                    "成绩：".$res['score']."\n".
                                    "考点：".$res['exampoint'];
                }else{
                    $contentStr = "您输入的查询信息无法找到对应的成绩信息，请重新确认准考证号和考试地点！格式如："."\n"."DMZ20170102001+白云考点";
                }
                $msgType = "text";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            }else{
                $msgType = "text";
                $contentStr = "查询成绩请输入准考证号和考试地点， 格式如:"."\n"."DMZ20170102001+白云考点";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            }
        }else{
            $contentStr = "您输入的查询信息无法找到对应的成绩信息，请重新确认准考证号和考试地点！格式如："."\n"."DMZ20170102001+白云考点";
            $msgType = "text";
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            echo $resultStr;
        }
        
    }
    
    public function handleEvent($object)
    {
        header("Content-Type:text/html;Charset=utf-8");
        $contentStr = "";
        switch ($object->Event)
        {
            case "subscribe":
                if($this->getDateTime()){
                    $contentStr = "感谢您的关注大拇指教育！";
                }else{
                    $contentStr = "感谢您的关注大拇指教育！"."\n"."查询成绩请输入准考证号和考点， 格式如:"."\n"."DMZ20170102001+白云考点";
                }
                break;
            case "unsubscribe":
                break;
            case "CLICK":
                switch ($object->EventKey){
                    case "search":
                        if($this->getDateTime()){
                            $contentStr = "目前还不能查询成绩哦！\n"."查询时间：2017年1月18日 8:00";
                        }  else {
                            $contentStr = "查询成绩请输入准考证号和考点， 格式如:"."\n"."DMZ20170102001+白云考点";
                        }
                        break;
                    default :
                        $contentStr = "感谢您的关注大拇指教育！";
                        break;
                }
                break;
            default:
                //$contentStr = "Unknow Event: ".$object->Event;
                if($this->getDateTime()){
                    $contentStr = "目前还不能查询成绩哦！\n"."查询时间：2017年1月18日 8:00.";
                }  else {
                    $contentStr = "查询成绩请输入准考证号和考点， 格式如:"."\n"."DMZ20170102001+白云考点";
                }
                break;
        }
        $resultStr = $this->responseText($object, $contentStr);
        return $resultStr;
    }
    
    public function responseText($object, $content, $flag=0)
    {
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>%d</FuncFlag>
                    </xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }


    //判断输入的数据格式是否正确
    function DataFormat($data){
        $arr = explode("+", $data);
        if(count($arr) == 2){
            return TRUE;
        }  else {
            return FALSE;
        }
    }
    
    //获取输入字符串数据并转换为数组，去除数组内容中的空格
    function getDateArr($data){
        $arr = explode("+", $data);
        $arr[0] = trim($arr[0]);
        $arr[1] = trim($arr[1]);
        return $arr;
    }
    
    //通过访问数据库获取成绩数据
    function getScoreByConnectSQL($searchData1,$searchData2){
        /*
        $searchData[0] = "张三";
        $searchData[1] = "姚江小学";
        $searchData[2] = "女";
        $searchData[3] = "302";
         * 
         */
        $return = $this->Data_model->get_single_data(array("examnum"=>$searchData1,"exampoint"=>$searchData2),"dmz_score");
        return $return;
    }
    
    //判断时间
    //return true  现在时间早于1月18号  
    //return false 现在时间晚于1月18号
    function getDateTime(){
        date_default_timezone_set('Asia/Shanghai'); 
        $date1 = date("y-m-d h:i:s");
        $date2 = "2017-1-18 08:00:00";
        if(strtotime($date1)<strtotime($date2)){
            return true;
        }else{
            return false;
        }
    }
}
?>